<template>
  <div class="dcs-container">
    <!-- Page Title Tabs (Assuming these are handled by a parent layout/component) -->
    <!-- <div class="dcs-page-tabs"> ... </div> -->

    <div class="dcs-grid-layout">
      <!-- Top Left: Deviation Reason Binning -->
      <div class="dcs-grid-item dcs-card">
        <div class="dcs-card-header">
          <span>钢种统计</span>
          <div class="dcs-header-buttons">
            <el-button-group size="small">
              <el-button :type="topLeftDateRange === 'day' ? 'primary' : 'default'" @click="topLeftDateRange = 'day'">按日</el-button>
              <el-button :type="topLeftDateRange === 'week' ? 'primary' : 'default'" @click="topLeftDateRange = 'week'">按周</el-button>
              <el-button :type="topLeftDateRange === 'month' ? 'primary' : 'default'" @click="topLeftDateRange = 'month'">按月</el-button>
            </el-button-group>
          </div>
        </div>
        <div class="dcs-card-body">
          <el-table :data="reasonBinTableData" size="small" border height="180" :header-cell-style="tableHeaderStyle">
            <el-table-column prop="ruleNo" label="规则号" width="60" />
            <el-table-column prop="steelGrade" label="钢种" width="150" />
            <el-table-column prop="width" label="宽度" width="100" />
            <el-table-column prop="thickness" label="厚度" width="80" />
            <el-table-column prop="deviationFreq" label="跑偏频率" width="80">
              <template #default="scope">{{ scope.row.deviationFreq.toFixed(3) }}</template>
            </el-table-column>
            <el-table-column prop="deviatingCoils" label="跑偏卷数" width="80" />
            <el-table-column prop="totalCoils" label="总卷数" width="70" />
          </el-table>
        </div>
      </div>

      <!-- Top Right: Top Specs Chart (Reason/Location) -->
      <div class="dcs-grid-item dcs-chart-card">
         <div class="dcs-card-header">
           <span>跑偏概率最高的几类品规</span>
           <div class="dcs-header-controls">
              <el-radio-group v-model="topRightChartType" size="small">
                <el-radio-button label="reason">跑偏原因</el-radio-button>
                <el-radio-button label="location">跑偏位置</el-radio-button>
              </el-radio-group>
           </div>
         </div>
         <div class="dcs-chart" ref="topRightChartRef"></div>
      </div>

      <!-- Middle Left: Deviation Reason Classification -->
      <div class="dcs-grid-item dcs-card">
        <div class="dcs-card-header">
          <span>跑偏原因分类</span>
           <div class="dcs-header-buttons">
             <el-select v-model="midLeftReasonClass" placeholder="跑偏原因分类" size="small" style="width: 140px; margin-right: 10px;">
               <el-option label="分类 A" value="A"></el-option>
               <el-option label="分类 B" value="B"></el-option>
             </el-select>
             <el-button-group size="small">
               <el-button :type="midLeftDateRange === 'day' ? 'primary' : 'default'" @click="midLeftDateRange = 'day'">按日</el-button>
               <el-button :type="midLeftDateRange === 'week' ? 'primary' : 'default'" @click="midLeftDateRange = 'week'">按周</el-button>
               <el-button :type="midLeftDateRange === 'month' ? 'primary' : 'default'" @click="midLeftDateRange = 'month'">按月</el-button>
             </el-button-group>
           </div>
        </div>
        <div class="dcs-card-body">
           <el-table :data="reasonClassTableData" size="small" border height="180" :header-cell-style="tableHeaderStyle">
             <!-- Columns similar to top-left table -->
             <el-table-column prop="ruleNo" label="规则号" width="60" />
             <el-table-column prop="steelGrade" label="钢种" width="150" />
             <el-table-column prop="width" label="宽度" width="100" />
             <el-table-column prop="thickness" label="厚度" width="80" />
             <el-table-column prop="deviationFreq" label="跑偏频率" width="80">
                <template #default="scope">{{ scope.row.deviationFreq.toFixed(3) }}</template>
             </el-table-column>
             <el-table-column prop="deviatingCoils" label="跑偏卷数" width="80" />
             <el-table-column prop="totalCoils" label="总卷数" width="70" />
           </el-table>
        </div>
      </div>

      <!-- Middle Right: Top Specs Chart (Steel Grade/Location) -->
       <div class="dcs-grid-item dcs-chart-card">
         <div class="dcs-card-header">
           <span>跑偏概率最高的几类品规</span> <!-- Title might need adjustment based on selection -->
           <div class="dcs-header-controls">
              <el-radio-group v-model="midRightChartType" size="small">
                <el-radio-button label="steelGrade">钢种</el-radio-button>
                <el-radio-button label="location">跑偏位置</el-radio-button>
              </el-radio-group>
           </div>
         </div>
         <div class="dcs-chart" ref="midRightChartRef"></div>
      </div>

      <!-- Bottom Left: Daily Trend by Steel Grade -->
       <div class="dcs-grid-item dcs-chart-card">
         <div class="dcs-card-header">钢种每日跑偏趋势图</div>
         <div class="dcs-chart" ref="bottomLeftChartRef"></div>
      </div>

      <!-- Bottom Middle: Daily Trend by Reason -->
       <div class="dcs-grid-item dcs-chart-card">
          <div class="dcs-card-header">跑偏原因每日跑偏趋势图</div>
         <div class="dcs-chart" ref="bottomMidChartRef"></div>
      </div>

      <!-- Bottom Right: Conclusion -->
      <div class="dcs-grid-item dcs-card dcs-conclusion-card">
         <div class="dcs-card-header">结论</div>
         <div class="dcs-conclusion-content">
           <p>{{ conclusionText }}</p>
         </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts/core';
import {
  BarChart,
  LineChart,
  BarSeriesOption,
  LineSeriesOption
} from 'echarts/charts';
import {
  TooltipComponent,
  GridComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import type { EChartsOption } from 'echarts';

echarts.use([
  TooltipComponent,
  GridComponent,
  LegendComponent,
  TitleComponent,
  BarChart,
  LineChart,
  CanvasRenderer
]);

// --- Data Refs ---
const topLeftDateRange = ref('day');
const midLeftDateRange = ref('day');
const midLeftReasonClass = ref('A');
const topRightChartType = ref('reason');
const midRightChartType = ref('steelGrade');

const conclusionText = ref('结论内容：跑偏次数最多的是什么钢种，跑偏占比最多的是什么钢种，跑偏原因是什么，该类型跑偏呈现上升趋势，几号cpc跑偏次数最多，需重点关注'); // From image

// Mock Table Data
const createMockTableData = () => [
  { ruleNo: 353, steelGrade: 'TENS-2JHSS(TS<590Mpa)', width: '1600-1700', thickness: '0.6-0.8', deviationFreq: 0.875, deviatingCoils: 3, totalCoils: 3 },
  { ruleNo: 162, steelGrade: 'TENS-0JF钢', width: '1700-1800', thickness: '0.4-0.6', deviationFreq: 0.854, deviatingCoils: 40, totalCoils: 83 },
  { ruleNo: 153, steelGrade: 'TENS-0JF钢', width: '1600-1700', thickness: '0.6-0.8', deviationFreq: 0.854, deviatingCoils: 79, totalCoils: 100 },
  { ruleNo: 173, steelGrade: 'TENS-0JF钢', width: '1800', thickness: '0.6-0.8', deviationFreq: 0.844, deviatingCoils: 70, totalCoils: 100 },
  { ruleNo: 124, steelGrade: 'TENS-0JF钢', width: '1000-1200', thickness: '0.8-1.0', deviationFreq: 0.677, deviatingCoils: 72, totalCoils: 97 },
  { ruleNo: 343, steelGrade: 'TENS-2JHSS(TS<590Mpa)', width: '1400-1600', thickness: '0.6-0.8', deviationFreq: 0.610, deviatingCoils: 33, totalCoils: 100 },
];

const reasonBinTableData = reactive(createMockTableData());
const reasonClassTableData = reactive(createMockTableData());

const tableHeaderStyle = {
  background: '#eef1f6',
  color: '#606266',
  fontWeight: '500'
};

// --- Chart Refs and Instances ---
const topRightChartRef = ref<HTMLElement | null>(null);
const midRightChartRef = ref<HTMLElement | null>(null);
const bottomLeftChartRef = ref<HTMLElement | null>(null);
const bottomMidChartRef = ref<HTMLElement | null>(null);

let topRightChartInstance: echarts.ECharts | null = null;
let midRightChartInstance: echarts.ECharts | null = null;
let bottomLeftChartInstance: echarts.ECharts | null = null;
let bottomMidChartInstance: echarts.ECharts | null = null;

// --- Chart Options (Shared dark theme) ---
const getBaseChartOptions = (): EChartsOption => ({
  backgroundColor: '#fff', // Changed to white
  title: {
    // text: title, // Title might be redundant with card header
    show: false // Hide internal chart title
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' },
    backgroundColor: 'rgba(50,50,50,0.7)',
    borderColor: '#ccc',
    borderWidth: 1,
    textStyle: { color: '#303133' } // Dark text for tooltip
  },
  grid: {
    left: '10%',
    right: '8%',
    top: '15%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    axisLabel: { color: '#606266', fontSize: 10 }, // Darker axis labels
    axisLine: { lineStyle: { color: '#dcdfe6' } }, // Lighter axis line
    splitLine: { show: false }
  },
  yAxis: {
    type: 'value',
    axisLabel: { color: '#606266', fontSize: 10 },
    axisLine: { show: true, lineStyle: { color: '#dcdfe6' } },
    splitLine: { lineStyle: { color: '#e4e7ed', type: 'dashed' } } // Lighter grid lines
  },
  textStyle: {
    color: '#303133' // Default dark text color
  }
});

// --- Chart Initialization ---
const initCharts = () => {
  disposeCharts();

  // Top Right Chart (Bar)
  if (topRightChartRef.value) {
    topRightChartInstance = echarts.init(topRightChartRef.value);
    const data = [0.854, 0.854, 0.644, 0.677, 0.61, 0.585, 0.525, 0.515, 0.513]; // Sample data from image
    const categories = [353, 162, 153, 173, 124, 343, 227, 172, 265, 174]; // Categories from image
    const option = {
      ...getBaseChartOptions(),
      xAxis: { ...(getBaseChartOptions().xAxis as object), data: categories },
      yAxis: { ...(getBaseChartOptions().yAxis as object), max: 1.0 }, // Set max for probability
      series: [{
        data: data,
        type: 'bar' as const,
        barWidth: '60%',
        itemStyle: { color: '#409EFF' }, // Element Plus Blue
        label: { // Show value on top of bars
            show: true,
            position: 'top',
            formatter: '{c}',
            color: '#606266', // Dark label color
            fontSize: 9
        }
      }] as BarSeriesOption[]
    };
    topRightChartInstance.setOption(option as EChartsOption);
  }

  // Middle Right Chart (Bar) - Similar structure, potentially different data/categories
  if (midRightChartRef.value) {
    midRightChartInstance = echarts.init(midRightChartRef.value);
     const data = [0.875, 0.854, 0.854, 0.844, 0.677, 0.61, 0.585, 0.525, 0.515, 0.513]; // Sample data from image
     const categories = [353, 162, 153, 173, 124, 343, 227, 172, 265, 174]; // Categories from image
     const option = {
      ...getBaseChartOptions(),
      xAxis: { ...(getBaseChartOptions().xAxis as object), data: categories },
      yAxis: { ...(getBaseChartOptions().yAxis as object), max: 1.0 },
      series: [{
        data: data,
        type: 'bar' as const,
        barWidth: '60%',
        itemStyle: { color: '#67C23A' }, // Element Plus Green
         label: { // Show value on top of bars
            show: true,
            position: 'top',
            formatter: '{c}',
            color: '#606266',
            fontSize: 9
        }
      }] as BarSeriesOption[]
    };
    midRightChartInstance.setOption(option as EChartsOption);
  }

  // Bottom Left Chart (Line) - Placeholder
  if (bottomLeftChartRef.value) {
    bottomLeftChartInstance = echarts.init(bottomLeftChartRef.value);
    const option = {
      ...getBaseChartOptions(),
      xAxis: { ...(getBaseChartOptions().xAxis as object), data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, // Example categories
      yAxis: { ...(getBaseChartOptions().yAxis as object), name: '跑偏次数' },
      series: [
        {
          name: 'Steel Grade A',
          type: 'line' as const,
          smooth: true,
          data: [12, 5, 8, 15, 10, 20, 18],
          lineStyle: { color: '#E6A23C' } // Element Plus Orange
        },
        {
          name: 'Steel Grade B',
          type: 'line' as const,
          smooth: true,
          data: [8, 10, 6, 9, 14, 12, 11],
          lineStyle: { color: '#F56C6C' } // Element Plus Red
        }
      ] as LineSeriesOption[]
    };
    bottomLeftChartInstance.setOption(option as EChartsOption);
  }

  // Bottom Middle Chart (Line) - Placeholder
  if (bottomMidChartRef.value) {
    bottomMidChartInstance = echarts.init(bottomMidChartRef.value);
     const option = {
      ...getBaseChartOptions(),
      xAxis: { ...(getBaseChartOptions().xAxis as object), data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
      yAxis: { ...(getBaseChartOptions().yAxis as object), name: '跑偏次数' },
      series: [
        {
          name: 'Reason X',
          type: 'line' as const,
          smooth: true,
          data: [5, 15, 12, 8, 10, 9, 13],
          lineStyle: { color: '#909399' } // Element Plus Gray
        },
         {
          name: 'Reason Y',
          type: 'line' as const,
          smooth: true,
          data: [10, 3, 6, 11, 9, 16, 10],
          lineStyle: { color: '#b3e19d' } // Lighter Green
        }
      ] as LineSeriesOption[]
    };
    bottomMidChartInstance.setOption(option as EChartsOption);
  }
};

const disposeCharts = () => {
  topRightChartInstance?.dispose();
  midRightChartInstance?.dispose();
  bottomLeftChartInstance?.dispose();
  bottomMidChartInstance?.dispose();
  topRightChartInstance = null;
  midRightChartInstance = null;
  bottomLeftChartInstance = null;
  bottomMidChartInstance = null;
};

const handleResize = () => {
  topRightChartInstance?.resize();
  midRightChartInstance?.resize();
  bottomLeftChartInstance?.resize();
  bottomMidChartInstance?.resize();
};

// --- Watchers for data changes (Example) ---
watch([topLeftDateRange, midLeftDateRange, midLeftReasonClass, topRightChartType, midRightChartType], () => {
  // TODO: Add logic to fetch new data based on selections
  console.log('Filters changed, fetching new data...');
  // Simulate data update and re-init charts
  reasonBinTableData.splice(0, reasonBinTableData.length, ...createMockTableData().reverse()); // Example update
  reasonClassTableData.splice(0, reasonClassTableData.length, ...createMockTableData()); // Example update
  nextTick(initCharts);
}, { deep: true });

// --- Lifecycle Hooks ---
onMounted(() => {
  nextTick(initCharts);
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  disposeCharts();
});

</script>

<style scoped>
.dcs-container {
  padding: 15px;
  background-image: linear-gradient(to top, white, #e6f0ff); /* Light gradient background */
  height: 100vh; /* Full height */
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  font-family: 'Microsoft YaHei', sans-serif;
}

.dcs-grid-layout {
  flex-grow: 1;
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* Changed to three columns */
  grid-template-rows: auto auto auto; /* Keep auto rows */
  gap: 15px;
  overflow: auto; /* Allow scrolling if content overflows */
}

.dcs-grid-item {
  display: flex;
  flex-direction: column;
  border-radius: 4px;
  overflow: hidden;
}

/* Card style for tables and conclusion */
.dcs-card {
  background-color: #fff; /* White background for cards */
  border: 1px solid #e4e7ed;
}

.dcs-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f7fa; /* Light header background */
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  flex-shrink: 0;
}

.dcs-header-buttons,
.dcs-header-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* Reduce button group margins */
:deep(.el-button-group) {
  display: flex; /* Ensure buttons are inline */
}

.dcs-card-body {
  padding: 10px;
  flex-grow: 1;
  overflow: auto; /* Allow table scrolling */
}

/* Chart card style */
.dcs-chart-card {
  background-color: #fff; /* Changed to white background */
  border: 1px solid #e4e7ed; /* Match light card border */
}

.dcs-chart-card .dcs-card-header {
  background-color: #f5f7fa; /* Match light card header */
  border-bottom: 1px solid #e4e7ed;
  color: #303133; /* Match light card header text */
  font-size: 13px;
}

:deep(.dcs-chart-card .el-radio-button__inner) {
  background-color: #fff;
  border-color: #dcdfe6;
  color: #606266;
  font-size: 12px;
  padding: 6px 10px;
}
:deep(.dcs-chart-card .el-radio-button__original-radio:checked+.el-radio-button__inner) {
  background-color: #409EFF; /* Element Plus primary blue */
  border-color: #409EFF;
  color: #fff;
  box-shadow: -1px 0 0 0 #409EFF;
}
:deep(.dcs-chart-card .el-radio-button:first-child .el-radio-button__inner) {
    border-left: 1px solid #dcdfe6; /* Match light border */
}
:deep(.dcs-chart-card .el-radio-button__original-radio:checked+.el-radio-button__inner):hover {
    color: #fff;
}
:deep(.dcs-chart-card .el-radio-button__inner):hover {
    color: #409EFF; /* Element Plus primary blue for hover */
}

.dcs-chart {
  flex-grow: 1;
  min-height: 180px; /* Ensure chart has min height */
}

/* Conclusion area style */
.dcs-conclusion-content {
  padding: 15px;
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  flex-grow: 1;
  overflow-y: auto;
}

/* New style to make conclusion span full width */
.dcs-conclusion-card {
  grid-column: 1 / -1; /* Span all columns */
}

/* Table header style */
:deep(.el-table th.el-table__cell) {
    padding: 6px 0;
}
:deep(.el-table td.el-table__cell) {
    padding: 4px 0;
    font-size: 12px;
}

</style>
